package servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/newsimg.do")
@MultipartConfig
public class NewsimgServlet extends HttpServlet {

    private static final long serialVersionUID = 2L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

//        request.setCharacterEncoding("utf-8");
//        response.setCharacterEncoding("utf-8");
//        response.setContentType("text/html; charset=UTF-8");
        Collection<Part> collection = request.getParts();
        Iterator<Part> iter = collection.iterator();
        String fileName = null;
        if (iter.hasNext()) {
            Part part = iter.next();
            String partName = part.getName();
            System.out.println(partName + "," + part.getSize() + "," + part.getContentType());
            fileName = getFileName(part);
            if (fileName == null) return;
            System.out.println("文件名：" + fileName);
            part.write("C:/程序设计/JavaWeb/press-release-system/web/resources/newsimg/" + fileName);
        }
        response.setContentType("application/json");
        String json = "{\"errno\":0,\"data\":{\"url\":\"#imgPath\"}}";
        json = json.replace("#imgPath", request.getContextPath() + "/download.do?f=" + URLEncoder.encode(fileName, "utf-8"));
        response.getWriter().print(json);

    }

    public String getFileName(Part part) {
        if (part.getSize() == 0 || part.getContentType() == null) return null;
        String header = part.getHeader("Content-Disposition");//获得Content-Disposition的头信息
        int idx = header.lastIndexOf("filename=\"");//获取filename=“字符串的开始下标
        String fileName = header.substring(idx+"filename=\"".length(), header.length()-1);
        return fileName;
    }
}
